package com.dotstone.chipism.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import com.dotstone.chipism.R;
import com.dotstone.chipism.bean.Home;
import com.dotstone.chipism.bean.HttpURL;
import com.dotstone.chipism.dialog.SVProgressHUD;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.NetUtil;
import com.dotstone.chipism.util.SPUtils;
import com.dotstone.chipism.util.SocketManager;
import com.dotstone.chipism.util.ToastShow;
import com.dotstone.chipism.view.slidingfragmenu.BarUtils;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class AddHouseActivity extends BaseActivity {
	private LinearLayout mBackL;
	private TextView mTitleTv;
	private EditText mHouseEd;
	private Button mEnsureB;
	private TextView mStatusBar;
	private String hid1;
	private String hid2;
	private String homename1;
	private String homename2;
	private boolean changed1 = false;
	private boolean changed2 = false;
	private SVProgressHUD mSVProgressHUD;
	private int houseCount;

	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.confirm_btn:
			addhome();
			break;

		default:
			break;
		}
	}

	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				String name = msg.obj.toString();
				if (houseCount != 1) {
					if (name.equals(homename1)) {
						changed1 = true;
					}
					if (name.equals(homename2)) {
						changed2 = true;
					}
					if (changed1 && changed2) {
						Log.i("wmy", "请求房屋");
						getHouse1();
					}
				} else {
					getHouse1();
				}

				break;
			case 1:
				if (mSVProgressHUD.isShowing()) {
					ToastShow.Show(getApplicationContext(),
							getString(R.string.success));
					mSVProgressHUD.dismiss();
				}
				SocketManager.getInstance().clearSocket();
				DeviceManager.getInstance().clearDevice();
				DeviceManager.getInstance().clearHouse();
				DeviceManager.getInstance().clearRoom();
				DeviceManager.getInstance().clearOrder();
				if (DeviceManager.getInstance().getHome().size() == 1||houseCount==1) {
					Intent intent = new Intent(AddHouseActivity.this,
							MainActivity.class);
					startActivity(intent);
					finish();
				} else {
					finish();
				}
				break;
			default:
				break;
			}
		}
	};

	@Override
	public void initParms(Bundle parms) {
		// TODO Auto-generated method stub

	}

	@Override
	public View bindView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int bindLayout() {
		// TODO Auto-generated method stub
		return R.layout.activity_add_house;
	}

	@Override
	public void initView(View view) {
		// TODO Auto-generated method stub
		mBackL = $(R.id.back_layout);
		mStatusBar = $(R.id.tv_statusBar_mian);
		mHouseEd = $(R.id.homename_ed);
		mEnsureB = $(R.id.confirm_btn);
		mTitleTv = $(R.id.title_tv);
		mTitleTv.setVisibility(View.VISIBLE);
		mTitleTv.setText(getString(R.string.add_home));
		mTitleTv.setTextColor(getResources().getColor(R.color.text_login_blue));
		mBackL.setVisibility(View.GONE);
		boolVersion();
		mEnsureB.setOnClickListener(this);
		mHouseEd.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View arg0, boolean hasFocus) {
				// TODO Auto-generated method stub
				if (hasFocus) {
					mHouseEd.setText("");
					mHouseEd.setHint("");
				} else {
					if (mHouseEd.getText().toString().length() == 0) {
						mHouseEd.setHint(getString(R.string.house_name1));
					}
				}
			}
		});
		mSVProgressHUD = new SVProgressHUD(AddHouseActivity.this);
	}

	public void boolVersion() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

			Window window = getWindow();
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
//			getWindow().addFlags(
//					WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			// 改变titlebar的高度
			int statusbarHeight = BarUtils.getStatusBarHeight(this);
			RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) mStatusBar
					.getLayoutParams();
			layoutParams1.height = statusbarHeight;
			mStatusBar.setLayoutParams(layoutParams1);
			mStatusBar.setVisibility(View.VISIBLE);
		} else {
			mStatusBar.setVisibility(View.GONE);
		}
	}

	@Override
	public void setListener() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doBusiness(Context mContext) {
		// TODO Auto-generated method stub

	}

	private void addhome() {
		// 先判断是否有网
		// 再判断名字是否符合标准
		homename2 = mHouseEd.getText().toString().trim();
		List<Home> mHomes = new ArrayList<Home>();
		mHomes = DeviceManager.getInstance().getAllHome();
		Log.i("wmy", "homename2 = "+homename2+" mHomes.size()= "+mHomes.size());
		for (int i = 0; i < mHomes.size(); i++) {
			if (homename2.equals(mHomes.get(i).getHomeName())) {
				ToastShow.Show(getApplicationContext(),
						getString(R.string.home_name_same));
				return;
			}
		}
		if (TextUtils.isEmpty(homename2)) {
			Toast toast = Toast.makeText(getApplicationContext(),
					getResources().getString(R.string.home_not_null),
					Toast.LENGTH_SHORT);
			toast.show();
			return;
		}
		if (homename2.length() < 2 || homename2.length() > 16) {
			ToastShow.Show(getApplicationContext(),
					getString(R.string.home_name_short));
			return;
		}
		if (NetUtil.isNetworkAvailable(this)) {
			mSVProgressHUD.showWithStatus("正在提交");
			RequestParams params = new RequestParams(HttpURL.HANDLE_HOME_URL);
			params.setAsJsonContent(true);
			JSONObject obj = new JSONObject();
			String token = (String) SPUtils.get(getApplicationContext(),
					"token", "");
			try {
				obj.put("key", "10000");
				obj.put("homeName", homename2);
				obj.put("handleType", "1");
				obj.put("token", token);
				obj.put("requestTime", "" + System.currentTimeMillis());
				Log.d("test", "login obj = " + obj.toString());
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			params.setBodyContent(obj.toString());

			x.http().post(params, new Callback.CommonCallback<String>() {
				@Override
				public void onSuccess(String result) {
					Log.e("Tag", "成功=" + result);
					try {
						JSONObject jsonObject = new JSONObject(result);

						int resultCode = jsonObject.optInt("resultCode");

						if (resultCode == 1) {
							// 上传成功后，获取家庭列表，如果返回的家庭列表只有一个 将其状态改为1 直接跳转至主界面
							// 如果返回多个家庭 找出刚才上传的 将其状态改为1 当前家庭改为9 再跳转至主界面
							getHouse();
						} else {
							if (mSVProgressHUD.isShowing()) {
								mSVProgressHUD.dismiss();
							}
							String errorMsg = jsonObject.getString("errorMsg");
							ToastShow.Show(AddHouseActivity.this, errorMsg);
							throw new Exception();
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onError(Throwable ex, boolean isOnCallback) {
					Log.e("Tag", "错误" + ex.getMessage());
				}

				@Override
				public void onCancelled(CancelledException cex) {

				}

				@Override
				public void onFinished() {
					Log.e("Tag", "完成");
				}
			});
		} else {
			ToastShow.Show(getApplicationContext(),
					getString(R.string.nonetwork));
		}
	}

	private void getHouse() {
		RequestParams params = new RequestParams(HttpURL.GET_HOME_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("key", "10000");
			obj.put("token",
					(String) SPUtils.get(getApplicationContext(), "token", ""));
			obj.put("requestTime", "" + System.currentTimeMillis());
			Log.d("test", "get house obj = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());

		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.e("Tag", "成功=" + result);
				try {
					JSONObject jsonObject = new JSONObject(result);

					int resultCode = jsonObject.optInt("resultCode");

					if (resultCode == 1) {
						JSONArray ja = jsonObject.optJSONArray("data");
						houseCount = ja.length();
						if (ja.length() != 1) {
							for (int i = 0; i < ja.length(); i++) {
								String hid = ja.getJSONObject(i).getString(
										"hid");
								String userId = ja.getJSONObject(i).getString(
										"userId");
								String homeName = ja.getJSONObject(i)
										.getString("homeName");
								int status = ja.getJSONObject(i).getInt(
										"status");
								// 拿到当前房间的hid
								// 拿到刚才添加的房间的hid
								if (homeName.equals(homename2)) { // 从服务器请求回来的数据中
																	// 房屋名相同
																	// 取其hid
									hid1 = DeviceManager.getInstance().hid;
									hid2 = hid;
									homename1 = DeviceManager.getInstance().homeName;
									changeStatus(hid1, homename1, 9);
									changeStatus(hid2, homename2, 1);
									break;
									// DeviceManager.getInstance().homeName =
									// homeName;
									// DeviceManager.getInstance().hid = hid;
								}
								// Home home = new Home(hid, userId, homeName,
								// status);
								// DeviceManager.getInstance().addHome(home);
							}
						} else {
							String hid = ja.getJSONObject(0).getString("hid");
							String userId = ja.getJSONObject(0).getString(
									"userId");
							String homeName = ja.getJSONObject(0).getString(
									"homeName");
							int status = ja.getJSONObject(0).getInt("status");
							changeStatus(hid, homeName, 1);
						}

					} else {
						if (mSVProgressHUD.isShowing()) {
							mSVProgressHUD.dismiss();
						}
						String errorMsg = jsonObject.getString("errorMsg");
						ToastShow.Show(getApplicationContext(), errorMsg);
						throw new Exception();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {
				Log.e("Tag", "错误" + ex.getMessage());
				// 清空所有本地数据，进入MainActivity
				if (mSVProgressHUD.isShowing()) {
					mSVProgressHUD.dismiss();
				}
				ToastShow.Show(getApplicationContext(),
						getString(R.string.failed));
			}

			@Override
			public void onCancelled(CancelledException cex) {

			}

			@Override
			public void onFinished() {
				Log.e("Tag", "完成");
			}
		});
	}

	private void changeStatus(String hid, final String name, int status) {
		if (NetUtil.isNetworkAvailable(this)) {
			RequestParams params = new RequestParams(HttpURL.HANDLE_HOME_URL);
			params.setAsJsonContent(true);
			JSONObject obj = new JSONObject();
			String token = (String) SPUtils.get(getApplicationContext(),
					"token", "");
			try {
				obj.put("hid", hid);
				obj.put("key", "10000");
				obj.put("homeName", name);
				obj.put("handleType", "2");
				obj.put("token", token);
				obj.put("status", status);
				obj.put("requestTime", "" + System.currentTimeMillis());
				Log.d("test", "更改房屋状态 = " + obj.toString());
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			params.setBodyContent(obj.toString());

			x.http().post(params, new Callback.CommonCallback<String>() {
				@Override
				public void onSuccess(String result) {
					Log.e("Tag", "成功=" + result);
					try {
						JSONObject jsonObject = new JSONObject(result);

						int resultCode = jsonObject.optInt("resultCode");

						if (resultCode == 1) {
							Message msg = Message.obtain();
							msg.what = 0;
							msg.obj = name;
							mHandler.sendMessage(msg);

						} else {
							if (mSVProgressHUD.isShowing()) {
								mSVProgressHUD.dismiss();
							}
							String errorMsg = jsonObject.getString("errorMsg");
							ToastShow.Show(AddHouseActivity.this, errorMsg);
							throw new Exception();
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onError(Throwable ex, boolean isOnCallback) {
					if (mSVProgressHUD.isShowing()) {
						mSVProgressHUD.dismiss();
					}
					ToastShow.Show(getApplicationContext(), "网络错误！");
					Log.e("Tag", "错误" + ex.getMessage());
				}

				@Override
				public void onCancelled(CancelledException cex) {

				}

				@Override
				public void onFinished() {
					Log.e("Tag", "完成");
				}
			});
		} else {
			ToastShow.Show(getApplicationContext(),
					getString(R.string.nonetwork));
		}
	}

	private void getHouse1() {
		RequestParams params = new RequestParams(HttpURL.GET_HOME_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("key", "10000");
			obj.put("token",
					(String) SPUtils.get(getApplicationContext(), "token", ""));
			obj.put("requestTime", "" + System.currentTimeMillis());
			Log.d("test", "login obj = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());

		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.e("Tag", "成功=" + result);
				try {
					JSONObject jsonObject = new JSONObject(result);

					int resultCode = jsonObject.optInt("resultCode");
					DeviceManager.getInstance().clearHouse();
					if (resultCode == 1) {
						JSONArray ja = jsonObject.optJSONArray("data");

						for (int i = 0; i < ja.length(); i++) {
							String hid = ja.getJSONObject(i).getString("hid");
							String userId = ja.getJSONObject(i).getString(
									"userId");
							String homeName = ja.getJSONObject(i).getString(
									"homeName");
							int status = ja.getJSONObject(i).getInt("status");
							if (status == 1) {
								DeviceManager.getInstance().homeName = homeName;
								DeviceManager.getInstance().hid = hid;
							}
							Home home = new Home(hid, userId, homeName, status);
							DeviceManager.getInstance().addHome(home);
						}
						Message msg = Message.obtain();
						msg.what = 1;
						mHandler.sendMessage(msg);
						
					} else {
						String errorMsg = jsonObject.getString("errorMsg");
						ToastShow.Show(AddHouseActivity.this, errorMsg);
						if (mSVProgressHUD.isShowing()) {
							mSVProgressHUD.dismiss();
						}
						throw new Exception();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {
				// Log.e("Tag", "错误" + ex.getMessage());
				if (mSVProgressHUD.isShowing()) {
					mSVProgressHUD.dismiss();
				}
				ToastShow.Show(getApplicationContext(), "网络错误！");
			}

			@Override
			public void onCancelled(CancelledException cex) {

			}

			@Override
			public void onFinished() {
				Log.e("Tag", "完成");
			}
		});
	}
}
